package com.drunkoid.server;

import java.text.DecimalFormat;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.drunkoid.db.*;
public class ServerMgr {

	static ServerMgr loctionmgr=null;
	private static final int MIN_NEAR_USERS_TO_ACTIVATE = 1;
	//private static final double MAX_DISTANCE_SQUARE = 0.00000144; //0.0012^2, 100 meters radius
	private static final long MAX_TIME_MILLISEC = 60*60*1000; //60 minutes	
	DecimalFormat twoDForm = new DecimalFormat("#.##");

	//update the user's location 
	public int updateLocation(String id, double longitude, double latitude) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			UserDB uDB = new UserDB(id, longitude, latitude);
			pm.makePersistent(uDB);
			//validate insertion of user to the DB
			pm.getObjectById(UserDB.class, id);
			return 1;
		}
		catch (Exception e){
			return -1;
		}
		finally{
			//failed to add user
			pm.close();
		}
	}
	public int isNearCluster(String id, double longitude, double latitude) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<UserDB> uList;
		try {
			javax.jdo.Query q = pm.newQuery(UserDB.class);
			//TODO improve this condition
			q.setFilter("lastOkTime > currTime");
			q.declareParameters("int currTime");
			uList = (List<UserDB>) q.execute(System.currentTimeMillis() - MAX_TIME_MILLISEC);
			int count = 0;
			int size = uList.size();
			System.out.println("size="+size);
			for (int i = 0 ; i < size ; i ++) {
				UserDB tmpUser = uList.get(i);
				double tmpLtd = tmpUser.getLatitude();
				double tmpLgt = tmpUser.getLongitude();
				//if it's not me
				System.out.println("checking "+tmpUser.getKey());
				if (!id.equals(tmpUser.getKey())){
					// x^2+ y^2 <= r^2
					System.out.println("hi1");
					double r = Distance.calclateArc(latitude,longitude,tmpLtd, tmpLgt) * 1000;
					//leave only two digits after the decimal point
					r = Double.valueOf(twoDForm.format(r));
					System.out.println("distance of "+id+" from "+tmpUser.getKey()+": "+r);
					if (r <= 100){
						count++;
					}
				}
			}
			System.out.println("return = " + count);
			return count >= MIN_NEAR_USERS_TO_ACTIVATE ? count : -1;
		}
		catch(Exception e){
			return -1;
		}
		finally {
			pm.close();
		}
	}

	public static ServerMgr getInstance() {
		if (loctionmgr==null){
			loctionmgr = new ServerMgr();
		}
		return loctionmgr;
	}

}
